﻿using API.Models;
using Dapper;
using Files.Common;
using Files.Entity;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;

namespace API.Controllers
{
    public class FileController : ApiController
    {
        /// <summary>
        /// 参数选手（小组）列表
        /// </summary>
        /// <param name="key"></param>
        /// <param name="limit"></param>
        /// <param name="page"></param>
        /// <param name="CompetitionTypeId"></param>
        /// <param name="EventsId"></param>
        /// <param name="ParticipantsTypeId"></param>
        /// <returns></returns>

        [HttpPost, HttpGet, Route("api/File/queryGroup")]
        public IHttpActionResult queryGroup(string key, int limit, int page, int? CompetitionTypeId, int? EventsId, int? ParticipantsTypeId)
        {
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                StringBuilder sb1 = new StringBuilder();

                sb1.AppendFormat("select * from ZX_Group where 1=1");

                sb.AppendFormat(@"SELECT  g.Id,g.CompetitionTypeId,g.EventsId,g.ParticipantsTypeId,g.Organization,g.Members,
                                 g.Account, g.Password, g.Phone, g.Remark, g.IsEnable, g.InsertTime, g.UpdateTime,
                                 c.Name as CName, p.Name as PName, e.Name as EName
                                   FROM(SELECT TOP {0} * FROM ZX_Group ORDER BY Id ASC) g
                                   left join ZX_CompetitionType c on g.CompetitionTypeId = c.Id
                                 left join ZX_Events e
                                 on g.EventsId = e.id left
                                 join ZX_ParticipantsType p on g.ParticipantsTypeId = p.Id
WHERE g.Id NOT IN(SELECT TOP {1} Id FROM ZX_Group ORDER BY Id ASC)", limit * page, (page - 1) * limit);

                if (!string.IsNullOrEmpty(key))
                {
                    sb.AppendFormat("  and g.Organization like '%{0}%' or g.Members like '%{1}%'", key, key);
                    sb1.AppendFormat("  and Organization like  '%{0}%' or Members like '%{1}%'", key, key);
                }
                if (CompetitionTypeId != null)
                {
                    sb.AppendFormat("  and g.CompetitionTypeId ={0} ", CompetitionTypeId);
                    sb1.AppendFormat("  and CompetitionTypeId = {0} ", CompetitionTypeId);
                }
                if (EventsId != null)
                {
                    sb.AppendFormat("  and g.EventsId = {0} ", EventsId);
                    sb1.AppendFormat("  and EventsId = {0} ", EventsId);
                }
                if (ParticipantsTypeId != null)
                {
                    sb.AppendFormat("  and g.ParticipantsTypeId = {0} ", EventsId);
                    sb1.AppendFormat("  and ParticipantsTypeId = {0} ", EventsId);
                }
                List<ZX_Group> list = db.Query<ZX_Group>(sb.ToString(), null).ToList();

                List<ZX_Group> totalCount = db.Query<ZX_Group>(sb1.ToString(), null).ToList();
                var jsonResult = new { code = 0, msg = "", count = totalCount.Count, data = list };
                return Json(jsonResult);
            }
        }

        /// <summary>
        /// 附件列表
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost, HttpGet, Route("api/File/queryAttachment")]
        public IHttpActionResult queryAttachment(int limit, int page, int GroupId)
        {
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                StringBuilder sb1 = new StringBuilder();

                sb1.AppendFormat("select * from ZX_Attachment where GroupId='{0}'", GroupId);
                sb.AppendFormat(@" SELECT  A.* FROM  (SELECT TOP {0} * FROM ZX_Attachment ORDER BY InsertTime ASC  ) A 
WHERE A.Id NOT IN(SELECT TOP {1} Id FROM ZX_Attachment ORDER BY InsertTime ASC) and GroupId='{2}'", limit * page, (page - 1) * limit, GroupId);

                List<ZX_Attachment> list = db.Query<ZX_Attachment>(sb.ToString(), null).ToList();
                List<ZX_Attachment> totalCount = db.Query<ZX_Attachment>(sb1.ToString(), null).ToList();
                var jsonResult = new { code = 0, msg = "", count = totalCount.Count, data = list };
                return Json(jsonResult);
            }
        }

        #region[文档配置]

        /// <summary>
        /// 用户端---查看
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>

        [HttpPost, HttpGet, Route("api/File/queryResultConfigList")]
        public IHttpActionResult queryResultConfigList([FromBody] JObject obj)
        {
            string EventId = obj["EventId"].ToString();
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();

                //参赛人员获取菜单
                sb.AppendFormat(@"select * from ZX_ResultConfig where EventId = {0}", EventId);

                var list = db.Query<ZX_ResultConfig>(sb.ToString(), null).ToList();
                return Json(ToMenuJson(list, ""));
            }
        }

        private string ToMenuJson(List<ZX_ResultConfig> data, string parentId)
        {
            StringBuilder sbJson = new StringBuilder();
            sbJson.Append("[");
            List<ZX_ResultConfig> entitys = data.FindAll(t => t.ParentId == parentId);
            if (entitys.Count > 0)
            {
                foreach (var item in entitys)
                {
                    //string haschildren = item.IsParent == 1 ? "true" : "false";
                    string strJson = item.ToJson();
                    // strJson = strJson.Insert(strJson.Length - 1, ",\"hasChildren\":" + haschildren + "");
                    strJson = strJson.Insert(strJson.Length - 1, ",\"children\":" + ToMenuJson(data, item.Id) + "");
                    sbJson.Append(strJson + ",");
                }
                sbJson = sbJson.Remove(sbJson.Length - 1, 1);
            }
            sbJson.Append("]");
            return sbJson.ToString();
        }

        //管理端
        


        #endregion


        #region[文件上传-webuploader--未使用]
        [HttpPost, HttpGet, Route("api/File/Upload")]
        public IHttpActionResult Upload()
        {
            string fileName = System.Web.HttpContext.Current.Request["name"];
            string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.'));//设置临时存放文件夹名称
            int index = Convert.ToInt32(HttpContext.Current.Request["chunk"]);//当前分块序号
            var guid = HttpContext.Current.Request["guid"];//前端传来的GUID号
            int groupId = Convert.ToInt32(HttpContext.Current.Request["groupId"]);//用户Id

            //获取用户信息创建对应目录
            ZX_Group group = queryUserByGroupId(groupId);

            var year = DateTime.Now.Year;
            var dir = HttpContext.Current.Server.MapPath("~/" + group.CName + "/" + group.EName + "/" + year + "/" + group.Organization + "/" + group.Account + "(" + group.Members + ")" + "/");//文件上传目录

            //创建目录结束

            dir = Path.Combine(dir, fileRelName);//临时保存分块的目录
            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);
            string filePath = Path.Combine(dir, index.ToString());//分块文件名为索引名，更严谨一些可以加上是否存在的判断，防止多线程时并发冲突
            var data = HttpContext.Current.Request.Files["file"];//表单中取得分块文件
            string extension = data.FileName.Substring(data.FileName.LastIndexOf(".") + 1,
            (data.FileName.Length - data.FileName.LastIndexOf(".") - 1));//获取文件扩展名

            //if (data != null)//为null可能是暂停的那一瞬间 
            //{
            data.SaveAs(filePath + fileName);
            //}
            WebHelper.WriteCookie("extension", extension);

            return Json(new { data = 0 });
        }

        [HttpPost, HttpGet, Route("api/File/Merge")]
        public IHttpActionResult Merge()
        {
            var guid = HttpContext.Current.Request["guid"];//GUID
            var option = HttpContext.Current.Request["fileOption"]; //上传文件类型选项
            //获取用户信息创建对应目录\\
            int groupId = Convert.ToInt32(HttpContext.Current.Request["groupId"]);//用户Id

            //获取用户信息创建对应目录
            ZX_Group group = queryUserByGroupId(groupId);

            var year = DateTime.Now.Year;

            var uploadDir = HttpContext.Current.Server.MapPath("~/" + group.CName + "/" + group.EName + "/" + year + "/" + group.Organization + "/" + group.Account + "(" + group.Members + ")" + "/");

            //---end创建目录结束---end\\

            var fileName = HttpContext.Current.Request["fileName"];//文件名
            string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.'));
            var dir = Path.Combine(uploadDir, fileRelName);//临时文件夹          
            var files = System.IO.Directory.GetFiles(dir);//获得下面的所有文件
            var finalPath = Path.Combine(uploadDir, fileName);//最终的文件名（demo中保存的是它上传时候的文件名，实际操作肯定不能这样）
            var fs = new FileStream(finalPath, FileMode.Create);
            foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序，保证从0-N Write
            {
                var bytes = System.IO.File.ReadAllBytes(part);
                fs.Write(bytes, 0, bytes.Length);
                bytes = null;
                System.IO.File.Delete(part);//删除分块
            }
            fs.Flush();
            fs.Close();
            System.IO.Directory.Delete(dir);//删除文件夹

            //添加数据库记录
            ZX_Attachment attachment = new ZX_Attachment
            {
                Id = Guid.NewGuid().ToString().Replace("-", ""),
                SaveName = fileName,
                FilePath = dir,
                ExtensionName = "dox",
                FileSize = "1024kb",
                Remark = "",
                GroupId = groupId,
                IsDelete = 0,
                UpdateTime = DateTime.Now,
                InsertTime = DateTime.Now,
                Score = 0
            };

            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                Message ms = new Message();
                var excCount = db.Execute("insert into ZX_Attachment(Id,SaveName,FilePath,ExtensionName,FileSize,Remark,GroupId,IsDelete,UpdateTime,InsertTime,Score)values(@Id,@SaveName,@FilePath,@ExtensionName,@FileSize,@Remark,@GroupId,@IsDelete,@UpdateTime,@InsertTime,@Score) ", attachment);

                if (excCount > 0)
                {
                    ms.success = true;
                    ms.code = "1111";
                    ms.msg = "上传成功";
                }
                else
                {
                    ms.success = false;
                    ms.code = "0000";
                    ms.msg = "上传失败";
                }
                var result = new { data = ms };
                return Json(result);
            }
        }

        #endregion


        #region[文件上传]
        public ZX_Group queryUserByGroupId(int groupId)
        {
            using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat(@" SELECT g.Id,g.CompetitionTypeId,g.EventsId,g.ParticipantsTypeId,g.Organization,g.Members,
                                 g.Account, g.Password, g.Phone, g.Remark, g.IsEnable, g.InsertTime, g.UpdateTime,
                                 c.Name as CName, p.Name as PName, e.Name as EName
                                   FROM ZX_Group  g
                                   left join ZX_CompetitionType c on g.CompetitionTypeId = c.Id
                                 left join ZX_Events e
                                 on g.EventsId = e.id left
                                 join ZX_ParticipantsType p on g.ParticipantsTypeId = p.Id
WHERE g.Id = {0}", groupId);

                ZX_Group group = db.Query<ZX_Group>(sb.ToString(), null).FirstOrDefault();
                return group;
            }
        }


        [HttpPost, Route("api/File/postFiles")]
        public IHttpActionResult PostFiles()
        {
            Message ms = new Message();
            HttpFileCollection filelist = HttpContext.Current.Request.Files;
            int groupId = Convert.ToInt32(HttpContext.Current.Request["groupId"]);
            if (filelist != null && filelist.Count > 0)
            {
                for (int i = 0; i < filelist.Count; i++)
                {
                    HttpPostedFile file = filelist[i];
                    string filename = file.FileName;
                    //获取用户信息创建对应目录
                    ZX_Group group = queryUserByGroupId(groupId);
                    var year = DateTime.Now.Year;
                    var FilePath = HttpContext.Current.Server.MapPath("~/" + group.CName + "/" + group.EName + "/" + year + "/" + group.Organization + "/" + group.Account + "(" + group.Members + ")" + "/");

                    DirectoryInfo di = new DirectoryInfo(FilePath);
                    if (!di.Exists)
                    {
                        di.Create();
                    }
                    try
                    {
                        file.SaveAs(FilePath + filename);
                        //result.obj = (Tpath + FileName).Replace("\\", "/");
                        //添加数据库记录
                        ZX_Attachment attachment = new ZX_Attachment
                        {
                            Id = Guid.NewGuid().ToString().Replace("-", ""),
                            SaveName = filename,
                            FilePath = "/" + group.CName + "/" + group.EName + "/" + year + "/" + group.Organization + "/" + group.Account + "(" + group.Members + ")" + "/",
                            ExtensionName = "dox",
                            FileSize = "1024kb",
                            Remark = "",
                            GroupId = groupId,
                            IsDelete = 0,
                            UpdateTime = DateTime.Now,
                            InsertTime = DateTime.Now,
                            Score = 0
                        };

                        using (IDbConnection db = new SqlConnection(ConfigurationFiles.connectionString))
                        {

                            var excCount = db.Execute("insert into ZX_Attachment(Id,SaveName,FilePath,ExtensionName,FileSize,Remark,GroupId,IsDelete,UpdateTime,InsertTime,Score)values(@Id,@SaveName,@FilePath,@ExtensionName,@FileSize,@Remark,@GroupId,@IsDelete,@UpdateTime,@InsertTime,@Score) ", attachment);

                            if (excCount > 0)
                            {
                                ms.success = true;
                                ms.code = "1111";
                                ms.msg = "上传成功";
                                ms.data = "/" + group.CName + "/" + group.EName + "/" + year + "/" + group.Organization + "/" + group.Account + "(" + group.Members + ")" + "/";
                            }
                            else
                            {
                                ms.success = false;
                                ms.code = "0000";
                                ms.msg = "上传失败";
                                ms.data = "";
                            }
                        }
                    }
                    catch (Exception ex)
                    {

                        ms.success = false;
                        ms.code = "0000";
                        ms.msg = "上传失败" + ex.Message;
                    }
                }
            }
            else
            {
                ms.success = false;
                ms.code = "0000";
                ms.msg = "上传的文件信息不存在";
            }

            var result = new { data = ms };
            return Json(result);
        }
        #endregion

    }
}
